/**
 * @module  预约
 * @author xiong sha
 * @date 2020-12-23 13:31:26
 */

import React, { useState, useEffect } from 'react';
import { RouteComponentProps } from 'react-router';
import { DatePicker, List, Checkbox, Toast, Button } from 'antd-mobile';
import request from '@src/utils/request';
import moment from 'moment';
import './index.less';

const CheckboxItem = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;

interface IList {
  id: number;
  price: string;
  title: string;
  type: string;
}
const Appointment: React.FC<RouteComponentProps> = (props: RouteComponentProps) => {
  const tag = (props.match.params as any).tag;
  const date = (props.match.params as any).time;
  const [list, setList] = useState<IList[]>([]);
  const [selectList, setSelectList] = useState<number[]>([]);

  const getList = () => {
    console.log(tag, date)
    request('get', '/api/v1/times', {
      date,
      venueid: tag,
    }).then((res) => {
      if (res && res.code === 200) {
        setList(res.data);
      } else {
        Toast.fail(res.message);
      }
    });
  };

  const confirm = () => {
    request('post', '/api/v1/orders', {
      items: {
        tag,
        date: moment(date).format('YYYY-MM-DD'),
        remark: '',
        list: selectList,
      },
    }).then((res) => {
      if (res && res.code === 200) {
        const {
          no,
          total_amount,
          user: { account },
        } = res.data;
        props.history.push(`/pay?no=${no}&money=${total_amount}&account=${account}`);
      } else {
        Toast.fail(res.message);
      }
    });
  };
  const checkChange = (val) => {
    // 多选框选择
    const idList = selectList;
    const index = selectList.indexOf(val);
    if (index === -1) {
      idList.push(val);
    } else {
      idList.splice(index, 1);
    }
    setSelectList(idList);
  };

  useEffect(() => {
    getList();
  }, []);

  return (
    <div className="appointment">
      <List renderHeader={() => '预约日期'}>
        {list.map((i) => (
          // onChange={() => this.onChange(i.value)}
          <CheckboxItem
            onChange={() => checkChange(i.id)}
            disabled={!i.type}
            key={i.id}
            extra={`¥${i.price}`}
          >
            {i.title}
          </CheckboxItem>
        ))}
      </List>
      <Button type="primary" onClick={confirm} className="submit-btn">
        确定
      </Button>
    </div>
  );
};

export default Appointment;
